<?php

class InventoryItemForm extends InventoryForm
{
    const FIELD_ID                     = 'id';
    const FIELD_NAME                   = 'name';
    const FIELD_LIFETIME_IN_DAYS       = 'lifetime_in_days';
    const FIELD_LEFT_IN_STOCK          = 'left_in_stock';
    const FIELD_COUNTRY_OF_PRODUCTION  = 'country_of_production';
    const FIELD_COST_PER_DAY           = 'cost_per_day';
    const FIELD_ACTION                 = 'action';

    public function Bind()
    {
        $this->values = array();
        $this->values[self::FIELD_NAME] = Request::GetParam(self::FIELD_NAME);
        $this->values[self::FIELD_LIFETIME_IN_DAYS] = Request::GetParam(self::FIELD_LIFETIME_IN_DAYS);
        $this->values[self::FIELD_LEFT_IN_STOCK] = Request::GetParam(self::FIELD_LEFT_IN_STOCK);
        $this->values[self::FIELD_COUNTRY_OF_PRODUCTION] = Request::GetParam(self::FIELD_COUNTRY_OF_PRODUCTION);
        $this->values[self::FIELD_COST_PER_DAY] = Request::GetParam(self::FIELD_COST_PER_DAY);
        $this->values[self::FIELD_ACTION] = Request::GetParam(self::FIELD_ACTION);
        $this->isValid = $this->Validate();
    }

    public function Save()
    {
        $itemManager = new InventoryItemManager();
        $inventoryItem = new InventoryItem();
        $inventoryItem->SetName($this->values[self::FIELD_NAME]);
        $inventoryItem->SetLifeTimeInDays($this->values[self::FIELD_LIFETIME_IN_DAYS]);
        $inventoryItem->SetLeftInStock($this->values[self::FIELD_LEFT_IN_STOCK]);
        $inventoryItem->SetCountryOfProduction($this->values[self::FIELD_COUNTRY_OF_PRODUCTION]);
        $inventoryItem->SetCostPerDay($this->values[self::FIELD_COST_PER_DAY]);

        $idField = Request::GetParam(self::FIELD_ID);
        if (!empty($idField) && ($this->values[self::FIELD_ACTION] == 'update'))
        {
            $inventoryItem->SetId($idField);
            $itemManager->Update($inventoryItem);
        }
        else
        {
            $itemManager->Insert($inventoryItem);
        }
    }

    protected function Validate()
    {
        $isValid = true;

        foreach ($this->values as $fieldValue)
        {
            if (empty($fieldValue))
            {
                return false;
            }
        }

        $lifetime = $this->GetValue(self::FIELD_LIFETIME_IN_DAYS);
        $leftInStock = $this->GetValue(self::FIELD_LEFT_IN_STOCK);
        $costPerDay = $this->GetValue(self::FIELD_COST_PER_DAY);
        if ((!is_numeric($lifetime)) || (!is_numeric($leftInStock)) || (!is_numeric($costPerDay)
             || ($lifetime <= 0) || ($leftInStock <= 0) || ($costPerDay <= 0)
            ))
        {
            $isValid = false;
        }
        return $isValid;
    }

}